package com.nchu.commondevelopmentframework.common.security.manager;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nchu.commondevelopmentframework.entity.Menu;
import com.nchu.commondevelopmentframework.mapper.MenuMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.function.Supplier;

/**
 * @className: MyAuthorizationManager
 * @description: 动态权限校验  自定义实现check和verify方法
 * @author: Li Chuanwei
 * @date: 2024/02/09 0:34
 * @Company: Copyright [日期] by [作者或个人]
 **/
@Component
@Slf4j
public class MyAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {
    @Autowired
    private MenuMapper menuMapper;
    @Override
    public void verify(Supplier<Authentication> authentication, RequestAuthorizationContext object) {
        AuthorizationManager.super.verify(authentication, object);
    }

    @Override
    public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext object) {
        Collection<? extends GrantedAuthority> authorities = authentication.get().getAuthorities();

        //当前登录人的权限
        List<String> auths = authorities.stream().map(GrantedAuthority::getAuthority).toList();

        //访问的接口地址
        String requestURI = object.getRequest().getRequestURI();

        //查询当前请求的接口需要哪些权限能访问
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("menu_type",'F');
        queryWrapper.eq("url",requestURI);
        List<Menu> menus = menuMapper.selectList(queryWrapper);

        for (String auth : auths) {
            for (Menu menu : menus) {
                if(auth.equals(menu.getPerms())){
                    return new AuthorizationDecision(true);
                }
            }
        }
        log.info(authentication.get().getPrincipal() + ",没有访问:" + requestURI + "的权限");
        return new AuthorizationDecision(false);
    }
}
